<?php
require_once('../includes/settings.php');
require_once('../includes/functions.php');
require_once('../includes/repository.php');
require_once('../includes/sql.php');
deny_anonymous();
parameters_check($_REQUEST['action']);

function get_next_word($record_id){
	$sql = "SELECT * FROM `view_learning_items` WHERE record_id=? AND passed=0 LIMIT 1";
	$stmt = Repository::prepare($sql);
	$stmt -> bind_param('i',$record_id);
	$stmt -> execute();
	return Repository::get_result($stmt,TRUE);
}

function pass($item_id){
	$sql = "UPDATE `voca_daily_learning_items` SET passed=1 WHERE id=?";
	$stmt = Repository::prepare($sql);
	$stmt -> bind_param('i',$item_id);
	$stmt -> execute();
	return $stmt->affected_rows == 1; 
}

function get_random_definitions($word_id,$number=3){
	$sql='SELECT definition FROM voca_definitions AS r1 JOIN'.
		' (SELECT (RAND() * (SELECT MAX(id) FROM voca_definitions)) AS id) AS r2'.
		' WHERE r1.id >= r2.id and word_id!=?'.
		' LIMIT '.$number;
	$stmt = Repository::prepare($sql);
	$stmt -> bind_param('i',$word_id);
	$stmt -> execute();
	return Repository::get_result($stmt);
}

$action = isset($_REQUEST['action'])?$_REQUEST['action']:NULL;
if($action=='quiz'){
	$record_id = intval($_POST['record_id']);
	$word = get_next_word($record_id);
	if($word['familiarity']==3){
		$definitions=get_random_definitions($word['word_id']);
		$word['definitions']=$definitions;
	}
	Repository::close();
	_jsonp(TRUE,$word);
}elseif ($action=='pass') {
	$item_id = intval($_POST['item_id']);
	$word_id = intval($_POST['word_id']);
	pass($item_id);
	UserWord::incr_familiarity(user_val('id'),$word_id);
	Repository::commit();
	Repository::close();
	_jsonp(TRUE);
}
exit();

?> 